package ru.adhoc.truealarm.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.Uri;
import android.util.Log;

import ru.adhoc.truealarm.R;

/**
 * Created by Малюгин Сергей on 17.06.13.
 */
public class DbHelper extends SQLiteOpenHelper {

    private String LOG_TAG = "My";
    private static DbHelper mInstance = null;
    private final static int DB_VERSION = 1;


    public static DbHelper getInstance(Context ctx) {
        if (mInstance == null) {
            mInstance = new DbHelper(ctx.getApplicationContext());
        }
        return mInstance;
    }

    public DbHelper(Context context) {
        super(context, "TrueAlarmDB", null, DB_VERSION);
    }

    public void onCreate(SQLiteDatabase db) {
        createAlarmTable(db);
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {

    }

    private void createAlarmTable(SQLiteDatabase db) {

        db.execSQL("create table AlarmTable ("
                + "id integer primary key autoincrement,"
                + "time long,"
                + "comment text,"
                + "position integer,"
                + "vibrate integer,"
                + "interval integer,"
                + "sounduri text,"
                + "repdays text,"
                + "switch integer" + ");");
        Log.d(LOG_TAG, "--- onCreate BD AlarmTable ---");
    }

//dd new alarm
    public long insertAlarm(SQLiteDatabase db, long time, int position, int sw, String comment,
                            String uri, boolean vibrate, String repDays, int interval) {

        ContentValues cv = new ContentValues();
        cv.put("time", time);
        cv.put("position", position);
        cv.put("switch", sw);
        cv.put("comment", comment);
        cv.put("sounduri", uri);
        cv.put("interval", interval);
        cv.put("vibrate", (vibrate) ? 1 : 0);
        cv.put("repdays", repDays);
        long id = db.insert("AlarmTable", null, cv);
        //Log.d(LOG_TAG, "--- inserting row in AlarmTable ---");
        db.close();
        return id;
    }

//return all alarms
    public Cursor getAlarms (SQLiteDatabase db){
        Cursor c = db.query("AlarmTable", null, null, null, null, null, null);
        return c;
    }

// set on/of alarm; id - position alarm; setSW -  0 off; 1 on;
    public void setSwitch(SQLiteDatabase db, int id, int setSw){
        ContentValues cv = new ContentValues();
        cv.put("switch", setSw);
        db.update("AlarmTable", cv, "id = ?", new String[] { Integer.toString(id) });
        db.close();
    }

//return ones alarm by id
    public Cursor getOnesAlarm(SQLiteDatabase db, int id){
        String selection = "id = ?";
        String[] selectionArgs = {Integer.toString(id)};
        Cursor c = db.query("AlarmTable", null, selection, selectionArgs, null, null, null);
        return c;
    }

//refresh existing alarm
    public void setNewTime(SQLiteDatabase db, int id, long time,
                           String comm, boolean vibrate, String uri, String repDays, int interval){
        ContentValues cv = new ContentValues();
        cv.put("time", time);
        cv.put("comment", comm);
        cv.put("sounduri", uri);
        cv.put("interval", interval);
        cv.put("vibrate", (vibrate) ? 1 : 0);
        cv.put("repdays", repDays);
        db.update("AlarmTable", cv, "id = ?", new String[] { Integer.toString(id) });
        db.close();
    }

//delete alarm
    public void deleteAlarm(SQLiteDatabase db, int id){
        db.delete("AlarmTable", "id = ?", new String[] { Integer.toString(id) });
        db.close();
    }

//get count active alarms
    public int getCountActiveAlarms(SQLiteDatabase db){
        String selection = "switch = ?";
        String[] selectionArgs = {"1"};
        Cursor c = db.query("AlarmTable", null, selection, selectionArgs, null, null, null);
        int count = c.getCount();
        c.close();
        db.close();
        return count;
    }

//get uri by alarm id
    public Uri getAlarmSoundURI(SQLiteDatabase db, int id){
        String selection = "id = ?";
        String[] selectionArgs = {Integer.toString(id)};
        Cursor c = db.query("AlarmTable", null, selection, selectionArgs, null, null, null);
        String strUri = "";
        if(c.moveToFirst())
            strUri = c.getString(c.getColumnIndex("sounduri"));
        c.close();
        db.close();
        Uri defaultUri = Uri.parse("android.resource://ru.adhoc.truealarm/" + R.raw.nature);
        if(strUri.length() == 0)
            return  defaultUri;
        else
        return Uri.parse(strUri);
    }

//возвращает время ближайшего будильника
    public Long getNearAlarmTime(SQLiteDatabase db){
        Long time = 0L;
        String query = "SELECT MIN(time) AS max_time " +
                "FROM AlarmTable " +
                "WHERE " +
                "switch=?";
        Cursor c = db.rawQuery(query, new String[] {"1"});
        if(c.moveToFirst())
            time = c.getLong(c.getColumnIndex("max_time"));
        c.close();
        db.close();
        return time;
    }

//обновляет только время будильника, нужно для поддрежания актуальных времен в базе
//при включении и выключении будильника приводит время к текущей дате
    public void refreshAlarmTime(SQLiteDatabase db, long time, int id){
        ContentValues cv = new ContentValues();
        cv.put("time", time);
        db.update("AlarmTable", cv, "id = ?", new String[] { Integer.toString(id) });
        db.close();
    }

//Возвращает строку из номеров дней в которые недолжен срабатывать будильник
    public String getRepDays(SQLiteDatabase db, int id){
        String selection = "id = ?";
        String[] selectionArgs = {Integer.toString(id)};
        Cursor c = db.query("AlarmTable", null, selection, selectionArgs, null, null, null);
        String repDays = "";
        if(c.moveToFirst())
            repDays = c.getString(c.getColumnIndex("repdays"));
        c.close();
        db.close();
        if(repDays != null)
            return repDays;
        else
            return "";
    }

    public Cursor getActiveAlarms(SQLiteDatabase db){
        String selection = "switch = ?";
        String[] selectionArgs = {"1"};
        Cursor cursor = db.query("AlarmTable", null, selection, selectionArgs, null, null, null);
        return cursor;
    }

}
